package org.jeecg.modules.sggg.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.modules.sggg.entity.SgDevice;
import org.jeecg.modules.sggg.entity.SgDeviceRelevance;
import org.jeecg.modules.sggg.service.ISgDeviceService;
import org.jeecg.modules.system.entity.SysDepart;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.ISysDepartService;
import org.jeecg.modules.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @Description: 设备管理
 * @Author: jeecg-boot
 * @Date: 2023-03-19
 * @Version: V1.0
 */
@Api (tags = "设备管理")
@RestController
@RequestMapping ("/deviceRelevance/sgDevice")
@Slf4j
public class SgDeviceController extends JeecgController<SgDevice, ISgDeviceService> {
    @Autowired
    private ISgDeviceService sgDeviceService;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private ISysDepartService sysDepartController;

    /**
     * 分页列表查询
     *
     * @param sgDevice
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    //@AutoLog(value = "设备管理-分页列表查询")
    @ApiOperation (value = "设备管理-分页列表查询", notes = "设备管理-分页列表查询")
    @GetMapping (value = "/list")
    public Result<IPage<SgDevice>> queryPageList (SgDevice sgDevice, @RequestParam (name = "pageNo", defaultValue = "1") Integer pageNo, @RequestParam (name = "pageSize", defaultValue = "10") Integer pageSize, HttpServletRequest req) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        QueryWrapper<SgDevice> queryWrapper = QueryGenerator.initQueryWrapper(sgDevice, req.getParameterMap());

        //获取角色信息
        String roleCode = redisUtil.get("roleCode:" + sysUser.getId()).toString();

        SysDepart sysDepart = sysDepartController.getById(sysUser.getDepartIds());
        List<String> responsibleAgencies = new ArrayList<>();
        // 根据DeptAttr机构属性判断当前登录人属于哪个机构（三高之家、三高基地、三高中心）
        if(sysDepart !=null && sysDepart.getDeptAttr()!=null){
            SysUser sysUser1 = sysUserService.getById(sysUser.getId());
            // 1.三高之家
            if(sysDepart.getDeptAttr().equals("1")){
                queryWrapper.eq("doctor_id", sysUser.getId().toString());
            }
            // 2.三高基地
            if(sysDepart.getDeptAttr().equals("2")){
                String[] array = sysUser1.getResponsibleAgency().split(",");
                responsibleAgencies = Arrays.asList(array);
                queryWrapper.in("sys_org_code", responsibleAgencies);
            }
            // 3.三高中心
            if(sysDepart.getDeptAttr().equals("3")){
                String[] array = sysUser1.getResponsibleAgency().split(",");
                responsibleAgencies = Arrays.asList(array);
                queryWrapper.in("sys_org_code", responsibleAgencies);
            }
        }else if(roleCode.contains("dept_manage") || roleCode.contains("admin")){
            queryWrapper.eq("sys_org_code",sysUser.getOrgCode());

        }else{
            queryWrapper.eq("sys_org_code", sysUser.getOrgCode().toString());
        }

        queryWrapper.eq("is_delete", 0);
        Page<SgDevice> page = new Page<SgDevice>(pageNo, pageSize);
        IPage<SgDevice> pageList = sgDeviceService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 添加
     *
     * @param sgDevice
     * @return
     */
    @AutoLog (value = "设备管理-添加")
    @ApiOperation (value = "设备管理-添加", notes = "设备管理-添加")
    //@RequiresPermissions("deviceRelevance:sg_device:add")
    @PostMapping (value = "/add")
    public Result<String> add (@RequestBody SgDevice sgDevice) {
        sgDevice.setIsDelete(0);
        sgDeviceService.save(sgDevice);
        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param sgDevice
     * @return
     */
    @AutoLog (value = "设备管理-编辑")
    @ApiOperation (value = "设备管理-编辑", notes = "设备管理-编辑")
    //@RequiresPermissions("deviceRelevance:sg_device:edit")
    @RequestMapping (value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> edit (@RequestBody SgDevice sgDevice) {
        sgDeviceService.updateById(sgDevice);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog (value = "设备管理-通过id删除")
    @ApiOperation (value = "设备管理-通过id删除", notes = "设备管理-通过id删除")
    //@RequiresPermissions("deviceRelevance:sg_device:delete")
    @DeleteMapping (value = "/delete")
    public Result<String> delete (@RequestParam (name = "id", required = true) String id) {
        SgDevice sgDevice = new SgDevice();
        sgDevice.setId(id);
        sgDevice.setIsDelete(1);
        sgDeviceService.updateById(sgDevice);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog (value = "设备管理-批量删除")
    @ApiOperation (value = "设备管理-批量删除", notes = "设备管理-批量删除")
    //@RequiresPermissions("deviceRelevance:sg_device:deleteBatch")
    @DeleteMapping (value = "/deleteBatch")
    public Result<String> deleteBatch (@RequestParam (name = "ids", required = true) String ids) {
        String[] data = ids.split(",");
        for (int i = 0; i < data.length; i++) {
            SgDevice sgDevice = new SgDevice();
            sgDevice.setId(data[i]);
            sgDevice.setIsDelete(1);
            sgDeviceService.updateById(sgDevice);
        }

        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "设备管理-通过id查询")
    @ApiOperation (value = "设备管理-通过id查询", notes = "设备管理-通过id查询")
    @GetMapping (value = "/queryById")
    public Result<SgDevice> queryById (@RequestParam (name = "id", required = true) String id) {
        SgDevice sgDevice = sgDeviceService.getById(id);
        if (sgDevice == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(sgDevice);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param sgDevice
     */
    //@RequiresPermissions("deviceRelevance:sg_device:exportXls")
    @RequestMapping (value = "/exportXls")
    public ModelAndView exportXls (HttpServletRequest request, SgDevice sgDevice) {
        return super.exportXls(request, sgDevice, SgDevice.class, "设备管理");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    //@RequiresPermissions("deviceRelevance:sg_device:importExcel")
    @RequestMapping (value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel (HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, SgDevice.class);
    }


    /**
     * TODO     根据设备类型查询所有设备
     *
     * @param
     * @return
     * @author WangJie
     * @date 2023/3/19 17:11
     * @Exception
     */

    @ApiOperation (value = "根据设备类型查询所有设备", notes = "根据设备类型查询所有设备")
    @GetMapping (value = "/queryByType")
    public Result<List<SgDevice>> queryByType (int type) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        List<SgDevice> sgDevice = sgDeviceService.list(new QueryWrapper<SgDevice>().eq("sys_org_code", sysUser.getOrgCode()).eq("type", type).eq("is_delete",0));
        if (sgDevice == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(sgDevice);
    }

    /**
     * 根据设备类型查询所有设备,排除根据机构
     *
     * @param type
     * @return
     */
    @ApiOperation (value = "根据设备类型查询所有设备", notes = "根据设备类型查询所有设备")
    @GetMapping (value = "/queryByType_NoOrg")
    public Result<List<SgDevice>> queryByType_NoOrg (int type) {
        List<SgDevice> sgDevice = sgDeviceService.list(new QueryWrapper<SgDevice>().eq("type", type).eq("is_delete",0));
        if (sgDevice == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(sgDevice);
    }

    /**
     * 判断库存是否充足
     *
     * @param id
     * @return
     */
    @ApiOperation (value = "设备管理-判断库存是否充足", notes = "设备管理-判断库存是否充足")
    @GetMapping (value = "/isStock")
    public Result<SgDevice> isStock (@RequestParam (name = "id", required = true) String id) {
        SgDevice sgDevice = sgDeviceService.getById(id);
        if (sgDevice == null||sgDevice.getIsDelete().equals(1)) {
            return Result.error("设备信息异常!");
        }
        if (sgDevice.getStock() <= 0) {
            return Result.error("设备库存不足!");
        }
        return Result.OK("");
    }
}
